import { ref, reactive } from "vue"
export class GlobalInfo {
    /**用户登录后的token */
    static Token: string;
    static ServerUrl = process.env.ServerUrl;
    static RefreshTokenInterval = 600000;
    static isEditing = ref(false);
    static CurrentDocId = ref(0);
    static SubMenus = reactive(<any[]>[]);
    static Preview: any = null;
    static ScrollToActiveItemFun : ()=>void;

    static showError = (err: any) => {
        console.error("showError", err);
        alert(JSON.stringify(err));
    }

    static init = () => {
        if (GlobalInfo.ServerUrl == "..") {
            GlobalInfo.ServerUrl = `${location.protocol}//${location.host}`;
        }

    }

    /**登录 */
    static login = async (name: string, pwd: string) => {
        var ret = await fetch(`${GlobalInfo.ServerUrl}/Doc/Login`, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': GlobalInfo.Token
            },
            method: "POST",
            body: JSON.stringify({ Name: name, Password: pwd })
        });

        GlobalInfo.Token = await ret.text();
        console.log("登录结果：" + GlobalInfo.Token);
        window.setTimeout(GlobalInfo.refreshToken, GlobalInfo.RefreshTokenInterval);
    };

    static refreshToken = async () => {
        try {
            var ret = await fetch(`${GlobalInfo.ServerUrl}/Admin/RefrashToken`, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': GlobalInfo.Token
                },
                method: "GET"
            });

            GlobalInfo.Token = await ret.text();
            console.log("刷新结果：" + GlobalInfo.Token);
            window.setTimeout(GlobalInfo.refreshToken, GlobalInfo.RefreshTokenInterval);
        }
        catch (e) {
            window.setTimeout(GlobalInfo.refreshToken, 2000);
        }

    };

    static getContent = async (url: string): Promise<string> => {

        var ret = await fetch(`${GlobalInfo.ServerUrl}${url}`, {
            method: 'GET',
            headers: {
                'Authorization': GlobalInfo.Token
            }
        });
        if (ret.status != 200) {
            throw { statusCode: ret.status };
        }
        return await ret.text();

    };

    /**
     * 提交表单
     * @param url 根目录路径 如：/Doc
     * @param bodyObj 参数对象
     * @returns 服务器返回信息
     */
    static post = async (url: string, bodyObj: any): Promise<string> => {

        var bodyStr: string = "";

        if (bodyObj) {
            for (var pro in bodyObj) {
                var val = bodyObj[pro];
                if (val == undefined || val == null)
                    continue;
                if (bodyStr.length > 0)
                    bodyStr += "&";

                if (Array.isArray(val)) {
                    for (var i = 0; i < val.length; i++) {
                        if (i > 0)
                            bodyStr += "&";
                        bodyStr += pro + "=" + encodeURIComponent(val[i]);
                    }
                }
                else {
                    bodyStr += pro + "=" + encodeURIComponent(val);
                }
            }
        }
        var ret = await fetch(`${GlobalInfo.ServerUrl}${url}`, {
            method: 'POST',
            headers: {
                'Content-Type': "application/x-www-form-urlencoded",
                'Authorization': GlobalInfo.Token
            },
            body: bodyStr
        });
        if (ret.status != 200) {
            throw { statusCode: ret.status };
        }
        return await ret.text();

    };
}